<%
layout("/layouts/platform.html"){
%>

<style type="text/css">
    .layui-room-title {
        font-weight: bold;
        font-size: 18px;
        float: left;
    }

    .layui-room-number {
        position: absolute;
        right: 10px;
    }

    .active-number {
        color: green;
    }

    .room-user-list li {
        position: relative;
        height: 45px;
        line-height: 22px;
        padding: 10px 5px 10px 10px;
        border-bottom: 1px dotted #e2e2e2;
    }

    .room-user-list .fly-avatar {
        position: absolute;
        left: 10px;
        /*top: 15px;*/
    }

    .room-user-list .fly-avatar img {
        display: block;
        width: 45px;
        height: 45px;
        margin: 0;
        border-radius: 2px;
    }

    .room-user-list li.active {
        background-color: #F2F2F2;
    }

    .room-user-list li h2 {
        height: 26px;
        font-size: 0;
    }

    .room-user-list li h2 a {
        display: inline-block;
        max-width: 80%;
        padding-right: 10px;
        font-size: 14px;
    }

    .room-user-list li h2 .layui-badge {
        top: -2px;
        height: 16px;
        line-height: 16px;
        padding: 0 5px;
        margin-right: 10px;
        font-size: 12px;
        border: 1px solid #5FB878;
        background: none;
        color: #5FB878;
    }

    .room-user-list .room-user-message {
        position: relative;
        font-size: 12px;
        color: #999;
    }

    .room-user-info {
        position: relative;
        margin-left: 55px;
    }

    .message-time {
        font-size: 12px;
        position: absolute;
        right: 10px;
    }

    .room-user-remove {
        position: absolute;
        right: 0px;
        top: 0px;
        line-height: 65px;
        height: 65px;
        z-index: 99;
        width: 60px;
        text-align: center;
        background: #f2f2f2;
    }

    .room-user-remove i.layui-icon {
        font-size: 25px;
    }

    .room-user-remove i.layui-icon:hover {
        color: #FF5722;
    }

    .layui-col-left {
        width: 400px;
        float: left;
        position: relative;
    }

    .layui-col-center {
        position: relative;
        float: left;
        width: calc(100% - 400px);
    }

    .lay-room-name-edit {
        position: relative;
        vertical-align: top;
        width: 50px;
        height: 45px;
        line-height: 45px;
        display: inline-block;
        text-align: center;
    }

    .lay-room-name-edit i.layui-icon {
        font-size: 20px;
        color: #009E94;
    }

    .layui-room-content{
        padding: 0px;
        max-height: 500px;
        overflow: auto;
    }
</style>

<div class="layui-row" id="container">
    <div class="layui-card">
        <div class="layui-card-header">简介</div>
        <div class="layui-card-body">
            Websocket是一种用于 HTML5 浏览器的实时通讯协议，可以做到数据的实时推送，可适用于广泛的工作环境。
            WebSocket 使得客户端和服务器之间的数据交换变得更加简单，允许服务端主动向客户端推送数据。在 WebSocket API
            中，浏览器和服务器只需要完成一次握手，两者之间就直接可以创建持久性的连接，并进行双向数据传输
        </div>
    </div>
    <div class="layui-row">
        <div class="layui-col-left">
            <div class="layui-card">
                <div class="layui-card-header">
                    <div class="lay-room-list text-align-right">
                        <span title="刷新" @click="refreshRoom"><i class="layui-icon">&#xe669;</i></span>
                        <span title="添加房间" @click="addRoom"><i class="layui-icon">&#xe624;</i></span>
                        <span title="退出" @click="exitRoom"><i class="layui-icon">&#xe682;</i></span>
                    </div>
                </div>
                <div class="layui-card-body">
                    <div class="layui-collapse" id="roomView"  lay-filter="nav"></div>
                </div>

            </div>
        </div>
        <div class="layui-col-center">
            <div class="layui-card">
                <div class="layui-card-header">
                    消息中心
                </div>
                <div class="layui-card-body">
                    <div></div>
                    <div>
                        <form class="layui-form layui-form-pane" onsubmit="return false;">
                            <div class="layui-form-item layui-form-text">
                                <div class="layui-input-block">
                                    <textarea v-model="message" placeholder="发送内容"
                                              class="layui-textarea fly-editor" style="min-height: 200px"></textarea>
                                </div>
                            </div>

                            <button type="button"
                                    :class="{'layui-btn':true, 'layui-btn-fluid':true, 'layui-btn-danger':!disabled.send,'layui-btn-disabled':disabled.send}"
                                    :disabled="disabled.send">发送（Enter）
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div id="addRoomForm">
        <form class="add-room-form">
            <div class="layui-form-item">
                <label class="layui-form-label">名称</label>
                <div class="layui-input-block">
                    <input type="text" v-model="room.name" autocomplete="off"  class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">最大人数</label>
                <div class="layui-input-block">
                    <input type="text" v-model="room.maxNumber"  placeholder="请输入" autocomplete="off" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item layui-form-text">
                <label class="layui-form-label">简介</label>
                <div class="layui-input-block">
                    <textarea type="text" v-model="room.note"   placeholder="请输入" autocomplete="off" class="layui-textarea"></textarea>
                </div>
            </div>
        </form>
    </div>

</div>

<script type="text/html" id="roomTpl">
    {{#  if(d.length === 0){ }}
    无数据
    {{#  }else{ }}
    {{#  layui.each(d, function(index, item){ }}
        <div class="layui-colla-item">
            <h2 class="layui-colla-title" data-id="{{item.uuid}}">
                <div class="layui-room-title">{{item.name}}</div>
                <div class="layui-room-number">
                    {{#  if(!item.sysstate){ }}
                    <span onclick="vm.addUser('{{item.uuid}}')" class="lay-room-name-edit" title="添加人员"><i class="layui-icon">&#xe612;</i></span>
                    <span onclick="vm.editRoom('{{item.uuid}}')" class="lay-room-name-edit" title="编辑房间"><i class="layui-icon">&#xe642;</i></span>
                    {{#  } }}
                    <span class="active-number">{{item.online||0}}</span>/<span>{{item.maxnumber}}</span>
                </div>
            </h2>
            <div class="layui-colla-content layui-room-content {{#  if(index === 0){ }} layui-show {{# } }}"  id="{{item.uuid}}View"></div>
        </div>
    {{#  }); }}
    {{#  } }}

</script>

<script type="text/html" id="userTpl">
    {{#  if(d.length === 0){ }}
    无数据
    {{#  }else{ }}
    {{#  layui.each(d, function(index, userItem){ }}
    <ul class="room-user-list">
        <li class="{{index ==0 ? 'active':''}}">
            <a href="/u/55762896" class="fly-avatar">
                <img src="//thirdqq.qlogo.cn/g?b=oidb&amp;k=lopicjg6KnaRNbBgSTMzMLw&amp;s=100&amp;t=1555442689" alt="极璇">
            </a>
            <div class="room-user-info">
                <h2>
                    {{#  if(userItem.onlineState){ }}
                    <a class="layui-badge">在线</a>
                    {{#  } }}
                    <a class="room-user-name" href="/jie/64511/">{{userItem.name}}</a>
                    <span class="message-time">{{userItem.lastMessageTime}}</span>
                </h2>
                <div class="room-user-message">
                    <span>{{userItem.lastMessage}}</span>
                </div>
            </div>
            {{#  if(!userItem.sysstate){ }}
                <div title="移除房间" class="room-user-remove"><i class="layui-icon">&#x1007;</i></div>
            {{#  } }}
        </li>
    </ul>
    {{#  }); }}
    {{#  } }}

</script>

<script type="text/javascript">

    var vm ;
    layui.use(["form", "laytpl","element", "websocket","transfer"], function () {

        vm = new Vue({
            el: '#container',
            data: function () {
                return {
                    form: layui.form,
                    transfer: layui.transfer,
                    laytpl: layui.laytpl,
                    jquery: layui.jquery,
                    element: layui.element,
                    websocket: layui.websocket,
                    webSocket: {
                        ip: '127.0.0.1',
                        port: '8080',
                    },
                    room: {
                        uuid: "",
                        name: "",
                        note: "",
                        maxNumber: "",
                    },

                    currRoomId: '',
                    message: '',
                    disabled: {
                        send: true,
                        link: false,
                        close: true,
                    },
                    socket: null,
                    commRoomDataMap:{},
                    commUserDataList:[],
                    roomDataMapCache:{},
                    roomUserDataMapCache:{},
                }
            },
            watch: {},
            mounted: function () {
                var $this = this;
                layui.jquery($this.$el).removeClass("hide").addClass("show");
                $this.initForm();
                $this.link();
            }
            ,
            methods: {
                refreshRoom: function () {
                    this.exitRoom();
                    this.link();
                },
                exitRoom: function () {
                    var $this = this;
                    if ($this.socket) {
                        $this.socket.close();
                        $this.disabledFun();
                    }
                },
                renderTemplate: function (templateId, viewId, data, callback) {
                    var $this = this,
                        getTpl = document.getElementById(templateId).innerHTML,
                        view = document.getElementById(viewId);
                    $this.laytpl(getTpl).render(data, function (html) {
                        view.innerHTML = html;

                        if (/.*function.*/ig.test(Object.prototype.toString.call(callback))) {
                            callback.call(this, data);
                        }
                    });
                },
                openRoomWin: function (opt) {
                    var $this = this;
                    layer.open({
                        title: opt.title,
                        shade: 0,
                        content: $this.jquery("#addRoomForm"),
                        btn: ["确认", "取消"],
                        success: function (layero, index) {

                        },
                        yes: function (index, layero) {
                            if (opt.yesCallBack && /.*function.*/ig.test(Object.prototype.toString.call(opt.yesCallBack))) {
                                opt.yesCallBack.call($this, index, layero);
                            }
                        },
                        end:function () {
                            $this.jquery("#addRoomForm").addClass("hide");
                        }
                    });
                },
                getUserAll:function(){
                    var $this = this , dataArray = [], users = $this.commUserDataList;
                    $this.commUserDataList.forEach(function (row) {
                        dataArray.push( {"uuid": row.uuid, "name": row.name,checked:""})
                    })
                    return dataArray;
                },
                openRoomUserWin: function (opt) {
                    var $this = this;
                    layer.open({
                        title: opt.title,
                        shade: 0,
                        content: '<div id="addUserTransfer"></div>',
                        btn: ["确认", "取消"],
                        success: function (layero, index) {
                            //数据格式解析
                            $this.transfer.render({
                                id: 'addUserTransfer'
                                ,elem: '#addUserTransfer'
                                ,title: ['全部人员', '已选择人员']  //自定义标题
                                ,parseData: function(res){
                                    return {
                                        "value": res.uuid //数据值
                                        ,"title": res.name //数据标题
                                        ,"disabled": res.disabled  //是否禁用
                                        ,"checked": res.checked //是否选中
                                    }
                                }
                                ,data: $this.getUserAll()
                                ,height: 200
                            })

                        },
                        yes: function (index, layero) {
                            var userData = $this.transfer.getData('addUserTransfer'); //获取右侧数据
                            if(!userData.length){
                                layer.msg("请选择数据");
                                return false;
                            }
                            if (opt.yesCallBack && /.*function.*/ig.test(Object.prototype.toString.call(opt.yesCallBack))) {
                                opt.yesCallBack.call($this, userData , index, layero);
                            }
                        },
                        end:function () {
                            $this.jquery("#addRoomForm").addClass("hide");
                        }
                    });
                },
                addRoom: function () {
                    var $this = this;
                    $this.openRoomWin({
                        title:"添加房间",
                        yesCallBack: function (index, layero) {
                            $this.sendMsg({"action": "addOrEditRoom", data: $this.room});
                        }
                    })
                },
                findAllRoom: function () {
                    var $this = this;
                    $this.sendMsg({"action": "getRoom", data: {}});
                },
                findUserByRoom: function (roomId) {
                    var $this = this;
                    $this.sendMsg({"action": "findUserByRoomId", data: roomId});
                },
                addUser:function(roomId){
                    event.stopPropagation();
                    event.preventDefault();
                    var $this = this;
                    $this.currRoomId = roomId;
                    $this.openRoomUserWin({
                        title:"添加人员",
                        yesCallBack: function (data,index, layero) {
                            var userIds = [];
                            data.forEach(function (row) {
                                userIds.push(row.value)
                            });
                            $this.sendMsg({"action": "joinRoom", roomId: $this.currRoomId , userIds:userIds.join(",")});
                        }
                    });
                },
                editRoom:function(roomId){
                    event.stopPropagation();
                    event.preventDefault();
                    var $this = this , editData= $this.roomDataMapCache[roomId];
                    $this.room.maxNumber = editData["maxnumber"];
                    $this.room.uuid = editData["uuid"];
                    $this.room.name = editData["name"];
                    $this.room.note = editData["note"];
                    $this.currRoomId = roomId;
                    $this.openRoomWin({
                        title:"编辑房间",
                        yesCallBack: function (index, layero) {
                            $this.sendMsg({"action": "addOrEditRoom", data: $this.room});
                        }
                    });
                },
                sendMsg: function (dataJson) {
                    var $this = this;
                    if ($this.socket) {
                        $this.socket.send(JSON.stringify(dataJson));
                    }
                },
                initForm: function () {
                    var $this = this;
                    $this.form.render(null, "addForm");
                    $this.element.render('collapse');

                    //监听折叠
                    $this.element.on('collapse(nav)', function (data) {
                        if (data.show) {
                            var uuid = $this.jquery(data.title).attr("data-id");
                            if (uuid) {
                                $this.currRoomId = uuid;
                                $this.findUserByRoom(uuid);
                            }
                        }
                    });
                },
                disabledFun: function () {
                    var $this = this;
                    $this.disabled.send = true;
                    $this.disabled.link = false;
                    $this.disabled.close = true;
                },
                enableFun: function () {
                    var $this = this;
                    $this.disabled.send = false;
                    $this.disabled.link = true;
                    $this.disabled.close = false;
                },
                messageCallback: function (result) {
                    var $this = this;
                    if (!result.ok) {
                        return false;
                    }
                    var _data = result.msg || result.data;
                    if (_data == 0) {
                        layer.closeAll();
                        $this.findAllRoom();
                    } else if (_data == 3) {
                        $this.renderTemplate("roomTpl", "roomView", result.data, function () {
                            $this.initForm();
                            $this.commRoomDataMap = result.data[0];
                            result.data.forEach(function (row) {
                                $this.roomDataMapCache[row["uuid"]] = row;
                            })
                            $this.currRoomId = $this.commRoomDataMap.uuid;
                            $this.findUserByRoom($this.commRoomDataMap.uuid);
                        });
                    } else if (_data == 4) {
                        $this.renderTemplate("userTpl", $this.currRoomId + "View", result.data, function () {
                            $this.initForm();
                            result.data.forEach(function (row) {
                                $this.roomUserDataMapCache[$this.currRoomId] = row;
                            });
                            if($this.commRoomDataMap.uuid == $this.currRoomId){
                                $this.commUserDataList = result.data;
                            }
                        });
                    }else if(_data == 5){
                        $this.findUserByRoom($this.currRoomId);
                    }
                },
                link: function () {
                    var $this = this;
                    $this.socket = new $this.websocket({
                        domain: $this.webSocket.ip,
                        port: $this.webSocket.port,
                        protocol: 'db/room',
                        onInit: function (event) {
                            $this.enableFun();
                        },
                        onOpen: function (event) {
                            $this.findAllRoom();
                        },
                        onError: function (event) {
                        },
                        onSend: function (result) {
                        },
                        onclose: function (event) {
                            $this.disabledFun();
                        },
                        onMessage: function (result) {
                            $this.messageCallback(JSON.parse(result));
                        }
                    });
                }
            }
        });

    });
</script>

<%}%>